package com.douwong.student.fragment;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Handler;
import android.os.Message;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.LinearLayout;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.douwong.student.R;
import com.douwong.student.activity.QuestioAnswerShowActivity;
import com.douwong.student.adapter.AnswerQuestionExhangeAdapter;
import com.douwong.student.application.BaseApplication;
import com.douwong.student.base.BaseFragment;
import com.douwong.student.contant.CommonConfig;
import com.douwong.student.contant.NetConfig;
import com.douwong.student.interfaces.WorkResultNotify;
import com.douwong.student.model.AnswerQuestionInfo;
import com.douwong.student.model.ItemsEntity;
import com.douwong.student.model.RequestAction;
import com.douwong.student.popuwindow.UpLoadPopuWindow;
import com.douwong.student.task.QuestionAnswerListTask;
import com.douwong.student.utils.LogUtils;
import com.douwong.student.utils.NetUtils;
import com.douwong.student.utils.ToastUtils;
import com.douwong.student.view.MyCommonCallback;
import com.douwong.student.view.PullToRefreshListView;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.Executors;

import static com.douwong.student.R.id.all_ll;
import static com.douwong.student.R.id.blank_ll;
import static com.douwong.student.R.id.judge_ll;
import static com.douwong.student.R.id.mulps_ll;
import static com.douwong.student.R.id.single_ll;

/**
 * 问答互动碎片
 *
 * @author yichao
 */
@SuppressLint("ValidFragment")
public class AnswerQuestionExchangeFragment extends BaseFragment {
    private static final String TAG = "AnswerQuestionExchangeF";
    private int[] textView = new int[]{R.id.all_text, R.id.single_text, R.id.mulps_text, R.id.judge_text,
            R.id.blank_text};
    private View mContentView;
    private LinearLayout mAll_ll, mSingle_ll, mMulps_ll, mJudge_ll, mBlank_ll;
    private PullToRefreshListView mAnswer_listview;
    private Context mContext;
    private String mStartTime=null;
    private String mSubjectId=null;
    private String type=null;
    private BaseApplication mApplication;
    private UpLoadPopuWindow mLoadPopuWindow;
    private AnswerQuestionExhangeAdapter mAnswerQuestionExhangeAdapter;

    private final int SHOW_POPUWINDOW=2002;
    private final int DISMISS_POPUWINDOW=2003;
    private List<ItemsEntity> mDataList;
    private boolean mIsLoading;
    private int mCurrentPage=1;
    private Map<String, Object> mMap;


    @Override
    public void onAttach(Activity activity) {
        super.onAttach(activity);
        mContext = activity;
        mApplication = (BaseApplication) activity.getApplication();
    }

    private Handler mHandler=new Handler(){
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case SHOW_POPUWINDOW:
                    mLoadPopuWindow.showAtLocation(mContentView, Gravity.CENTER,0,0);
                    mLoadPopuWindow.setText("加载中...");
                    loadData(RequestAction.INIT,1,false);
                    break;
                case DISMISS_POPUWINDOW:
                    mLoadPopuWindow.dismiss();
                    break;
            }

        }
    };

    @Override
    protected View getRootView(LayoutInflater inflater, ViewGroup container) {
        mContentView = inflater.inflate(R.layout.answer_exchange_fragment_layout, null);
        mAll_ll = (LinearLayout) mContentView.findViewById(all_ll);
        mSingle_ll = (LinearLayout) mContentView.findViewById(single_ll);
        mMulps_ll = (LinearLayout) mContentView.findViewById(mulps_ll);
        mJudge_ll = (LinearLayout) mContentView.findViewById(judge_ll);
        mBlank_ll = (LinearLayout) mContentView.findViewById(blank_ll);
        mAnswer_listview = (PullToRefreshListView) mContentView.findViewById(R.id.answer_listview);
        return mContentView;
    }

    @Override
    protected void initData() {
        super.initData();
        mLoadPopuWindow = new UpLoadPopuWindow(mContext);
        mContext.registerReceiver(mReceiver,mFilter);
              mMap=new HashMap<>();
        showTextView(textView[0]);
        mDataList = new ArrayList<>();
        mAnswerQuestionExhangeAdapter = new AnswerQuestionExhangeAdapter(mContext,mDataList);

        mAnswer_listview.setAdapter(mAnswerQuestionExhangeAdapter);
        mHandler.sendEmptyMessageDelayed(SHOW_POPUWINDOW,500);


    }
    IntentFilter mFilter=new IntentFilter(){
        {
            addAction(CommonConfig.CLASS_RECORD_SERACH);
        }
    };
    BroadcastReceiver mReceiver=new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            switch (intent.getAction()) {
                case CommonConfig.CLASS_RECORD_SERACH:
                    mStartTime = intent.getStringExtra("start_time");
                    mSubjectId = intent.getStringExtra("subjectId");
                    break;
            }
        }
    };

    /**
     * 访问网络加载数据
     * @param retention 请求类型
     * @param currentPage 当前页数
     * @param isSearch 是否查找
     */
   private void loadData(final RequestAction retention, int currentPage, boolean isSearch){
       QuestionAnswerListTask questionAnswerListTask=new QuestionAnswerListTask(retention,
               isSearch,mApplication ,new WorkResultNotify<ItemsEntity>(
       ) {
           @Override
           public void notify(int stateCode, List<ItemsEntity> arryResult) {
               if (mLoadPopuWindow!=null && mLoadPopuWindow.isShowing()){
                 mHandler.sendEmptyMessage(DISMISS_POPUWINDOW);
               }
               if (RequestAction.INIT==retention){
                   //初始化
            //有数据 。     无数据。无网络
              if (stateCode==QuestionAnswerListTask.REQUESTOK){
                  mDataList.addAll(arryResult);
                  mAnswerQuestionExhangeAdapter.notifyDataSetChanged();
                   }else if (stateCode==QuestionAnswerListTask.NO_NETWOK){
                       ToastUtils.makeText(mContext,"请检查网络");
                   }

               }else if (RequestAction.REFRESH==retention){
                //刷新
                   if (stateCode==QuestionAnswerListTask.NO_NETWOK){

                       ToastUtils.makeText(mContext,"请检查网络");
                       mDataList.clear();
                       mAnswer_listview.onRefreshComplete();
                       mAnswerQuestionExhangeAdapter.notifyDataSetChanged();

                   }else if (stateCode==QuestionAnswerListTask.NO_DATA){
                       mDataList.clear();
                       mAnswer_listview.onRefreshComplete();
                       mAnswerQuestionExhangeAdapter.notifyDataSetChanged();

                   }else if (stateCode==QuestionAnswerListTask.REQUESTOK){

                       mDataList.clear();
                       mDataList.addAll(arryResult);
                       mAnswer_listview.onRefreshComplete();
                       mAnswerQuestionExhangeAdapter.notifyDataSetChanged();

                   }

               }else if (RequestAction.LOADMROE==retention){
                   //加载更多
                   mIsLoading=false;
                   if (stateCode==QuestionAnswerListTask.NO_NETWOK){
                        --mCurrentPage;
                       ToastUtils.makeText(mContext,"请检查网络");
                       mAnswer_listview.completeLoadMore();
                       mAnswerQuestionExhangeAdapter.notifyDataSetChanged();

                   }else if (stateCode==QuestionAnswerListTask.NO_DATA){
                       --mCurrentPage;
                       mAnswer_listview.completeLoadMore();
                       mAnswerQuestionExhangeAdapter.notifyDataSetChanged();
                       ToastUtils.makeText(mContext,"没有更多数据了");

                   }else if (stateCode==QuestionAnswerListTask.REQUESTOK){

                       mDataList.addAll(arryResult);
                       mAnswer_listview.completeLoadMore();
                       mAnswerQuestionExhangeAdapter.notifyDataSetChanged();

                   }


               }

           }
       });

       questionAnswerListTask.executeOnExecutor(Executors.newCachedThreadPool(),mSubjectId,type,mStartTime,currentPage+"");


    }

    @Override
    protected void initEvent() {
        super.initEvent();
        AnswerOnClick onClick = new AnswerOnClick();
        mAll_ll.setOnClickListener(onClick);
        mSingle_ll.setOnClickListener(onClick);
        mMulps_ll.setOnClickListener(onClick);
        mJudge_ll.setOnClickListener(onClick);
        mBlank_ll.setOnClickListener(onClick);
        mAnswer_listview.setOnRefreshListener(new PullToRefreshListView.OnRefreshListener() {
            @Override
            public void onRefresh() {
                mCurrentPage=1;
                loadData(RequestAction.REFRESH,mCurrentPage,false);
            }
        });
        mAnswer_listview.setOnILoadMoreListener(new PullToRefreshListView.OnILoadMoreListener() {
            @Override
            public void onLoadMore() {
if (!mIsLoading){
    ++mCurrentPage;
   loadData(RequestAction.LOADMROE,mCurrentPage,false);
}

            }
        });
        mAnswer_listview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, final int position, long id) {
                //点击事件  mMap = new HashMap<String, String>();
                mMap.clear();
                mMap.put("qa_interaction_id",mDataList.get(position-1).getId());
                mMap.put("student_id",BaseApplication.sUserBean.getUserbean().getId()+"");
                NetUtils.Post(NetConfig.QUESTIN_ANSWER_RECORD_INFO,mMap,new MyCommonCallback<String>(){

                    @Override
                    public void onSuccess(String result) {
                        super.onSuccess(result);
                        LogUtils.i(TAG,"问答互动信息 ："+result);
                        AnswerQuestionInfo sc = (AnswerQuestionInfo) JSON
                                .parseObject(result,
                                        new TypeReference<AnswerQuestionInfo>() {});
                        if (sc!=null){
                            if (sc.isFlag()){
                                List<AnswerQuestionInfo.DataEntity> data = sc.getData();
                                String resuleAnswer="";
                                if (data !=null  && data.size()==1){
                                    //有数据答案
                                    resuleAnswer = data.get(0).getResult();
                                }

                                ItemsEntity itemsEntity = mDataList.get(position - 1);
                                QuestioAnswerShowActivity.startActivity(mContext,itemsEntity.getTopic(),itemsEntity.getTopic_url(),
                                        itemsEntity.getOptions(),resuleAnswer,itemsEntity.getAnswer(),itemsEntity.getType()+"");
                            }else {
                                ToastUtils.makeText(mContext,sc.getMsg());
                            }
                        }



                    }

                    @Override
                    public void onError(Throwable ex, boolean isOnCallback) {
                        super.onError(ex, isOnCallback);
                        LogUtils.i(TAG,"问答互动信息失败 ："+ex.toString());
                    }
                });

            }
        });

    }

    private class AnswerOnClick implements View.OnClickListener {

        @Override
        public void onClick(View v) {
            switch (v.getId()) {
                // 全部
                case all_ll:
                    showTextView(textView[0]);
                    type="0";
                    break;
                // 单选
                case single_ll:
                    showTextView(textView[1]);
                    type="1";
                    break;
                // 多选
                case mulps_ll:
                    showTextView(textView[2]);
                    type="2";
                    break;
                // 判断
                case judge_ll:
                    showTextView(textView[3]);
                    type="15";
                    break;
            }
            mCurrentPage=1;
            mLoadPopuWindow.showAtLocation(v,Gravity.CENTER,0,0);
            loadData(RequestAction.REFRESH,mCurrentPage,false);
            mDataList.clear();
            mAnswerQuestionExhangeAdapter.notifyDataSetChanged();

        }
    }
        /**
         * 显示选择的条目
         */
        private void showTextView(int id) {
            for (int i = 0; i < textView.length; i++) {
                if (id == textView[i]) {
                    mContentView.findViewById(id).setVisibility(View.VISIBLE);
                } else {
                    mContentView.findViewById(textView[i]).setVisibility(View.INVISIBLE);
                }

            }
        }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        if (mReceiver!=null ){
        mContext.unregisterReceiver(mReceiver);
        }
        if (mLoadPopuWindow!=null &&mLoadPopuWindow.isShowing()){
            mLoadPopuWindow.dismiss();
        }

    }
}
